package com.cheyunkeji.er.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.activity.auction.HomeActivity;
import com.cheyunkeji.er.activity.evaluate.EvaluateHomePageActivity;
import com.cheyunkeji.er.activity.fast_evaluate.FastEvaluateActivity;
import com.cheyunkeji.er.adapter.GlideImageLoader;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.UserInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.utils.Utils;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.igexin.sdk.PushManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.core.app.ActivityCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

public class ModuleSelectActivity extends BaseActivity {


    private static final int REQUEST_PERMISSION = 0;

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.rl_fast_evaluate)
    RelativeLayout rlFastEvaluate;
    @BindView(R.id.rl_evaluate_all)
    RelativeLayout rlEvaluateAll;
    @BindView(R.id.rl_auction)
    RelativeLayout rlAuction;
    @BindView(R.id.banner)
    Banner banner;

    private UserInfo.ChannelListBean channelListBean = null;
    private String TAG = ModuleSelectActivity.class.getSimpleName();

    private int accessableModuleCount = 3;
    private List<Integer> images = new ArrayList<>();


    @Override
    protected void init() {
        setContentView(R.layout.er_activity_module_select);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) vTopbar.getLayoutParams();
            params.setMargins(0, Utils.dip2px(this, 20), 0, 0);
            vTopbar.setLayoutParams(params);
        }
        initGeTui();
        images.add(R.drawable.er_imag_1);
//        images.add(R.drawable.imag_2);
//        images.add(R.drawable.imag_3);
        banner.setImages(images).setImageLoader(new GlideImageLoader()).
                setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                //设置轮播时间
                .setDelayTime(5000).start();
        banner.stopAutoPlay();
    }

    private void initGeTui() {

//        PackageManager pkgManager = getPackageManager();
//        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
//        boolean sdCardWritePermission =
//                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
//
//        // read phone state用于获取 imei 设备信息
//        boolean phoneSatePermission =
//                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
//
//        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
//            requestPermission();
//        } else {
//            PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
//        }

//        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
//        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

        if (!TextUtils.isEmpty(PushManager.getInstance().getClientid(this))) {
            setTerminalMapping();
        }
    }


    /**
     * 每次登陆成功后需调用终端映射方法,为推送上传ClientID
     */
    private void setTerminalMapping() {

        HashMap<String, String> params = new HashMap<>();
        params.put("device", "1");
        params.put("clientid", PushManager.getInstance().getClientid(this));

        Log.e(TAG, " ====================== setTerminalMapping: Client ID : " + PushManager.getInstance().getClientid(this));

        ApiClient.postForm(HttpConstants.SET_GETUI_CLIENT, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                // 网络异常
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                try {

                    JSONObject obj = new JSONObject(response);

                    if (obj.optInt("code") == 1) {
                        Log.e(TAG, "onResponse: 上传clientID成功");
                    } else {
                        Log.e(TAG, "onResponse: 上传clientID失败");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
//                PushManager.getInstance().initialize(this.getApplicationContext(), DemoIntentService.class);
            } else {
                Log.e(TAG, "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                        + "functions will not work");
//                PushManager.getInstance().initialize(this.getApplicationContext(), DemoIntentService.class);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void initView() {

        vTopbar.setTitle("选择模块");
        vTopbar.setLeftBack();

        rlAuction.setOnClickListener(this);
        rlEvaluateAll.setOnClickListener(this);
        rlFastEvaluate.setOnClickListener(this);

        channelListBean = ChannelInfoUtil.getCurrentChannelInfo();

        if (null != channelListBean) {

            if (channelListBean.getIsrapid() == 0) {
                rlFastEvaluate.setVisibility(View.GONE);
                --accessableModuleCount;
            }
            if (channelListBean.getIsarchiver() == 0) {
                rlEvaluateAll.setVisibility(View.GONE);
                --accessableModuleCount;
            }
            if (channelListBean.getIsauction() == 0) {
                rlAuction.setVisibility(View.GONE);
                --accessableModuleCount;
            }
        }
        Log.e(TAG, "initView: Accessible Module Count : " + accessableModuleCount);
        if (accessableModuleCount == 1) {
            if (rlFastEvaluate.getVisibility() == View.VISIBLE) {
                MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_FAST_EVALUATE);
                startActivity(new Intent(this, FastEvaluateActivity.class));
            } else if (rlEvaluateAll.getVisibility() == View.VISIBLE) {
                MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_FULL_EVALUATE);
                startActivity(new Intent(this, EvaluateHomePageActivity.class));
            } else if (rlAuction.getVisibility() == View.VISIBLE) {
                MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_AUCTION);
                startActivity(new Intent(this, HomeActivity.class));
            }
            MyApplication.getInstance().removeActivity(this.getClass());
            finish();
        }
        else {
            //根据当前保存通道进入
            switch (MyApplication.getInstance().getCurrentModuleType()) {
                case Constants.CURRENT_MODULE_TYPE_FAST_EVALUATE:
                    startActivity(new Intent(this, FastEvaluateActivity.class));
                    break;
                case Constants.CURRENT_MODULE_TYPE_FULL_EVALUATE:
                    startActivity(new Intent(this, EvaluateHomePageActivity.class));
                    break;
                case Constants.CURRENT_MODULE_TYPE_AUCTION:
                    startActivity(new Intent(this, HomeActivity.class));
                    break;

                default:
                    break;
            }
        }

    }

    @Override
    protected void initData() {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_fast_evaluate:
                MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_FAST_EVALUATE);
                startActivity(new Intent(this, FastEvaluateActivity.class));
                break;
            case R.id.rl_evaluate_all:
                MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_FULL_EVALUATE);
                startActivity(new Intent(this, EvaluateHomePageActivity.class));
                break;
            case R.id.rl_auction:
                MyApplication.getInstance().setCurrentModuleType(Constants.CURRENT_MODULE_TYPE_AUCTION);
                startActivity(new Intent(this, HomeActivity.class));
                break;

            default:
                break;
        }
    }

}
